/**
 * Copyright &copy; 2018-2018 <a href="#">聚成科技</a> All rights reserved.
 */
package com.jckj.core.util;

import com.google.gson.Gson;
import com.jckj.core.contants.SysContants;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;

/**
 * <p>
 * 七牛上传工具类
 * </p>
 *
 * @author 刘志远
 * @date 18-1-26
 */
public class FileUploadUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(FileUploadUtils.class);

    public static String uploadFile(File file, String key) {
        String removeFilePath = "";
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);

        try {
            Auth auth = Auth.create(SysContants.QN_ACCESS_KEY, SysContants.QN_SECRET_KEY);
                String upToken = auth.uploadToken(SysContants.QN_BUCKET);
            try {
                FileInputStream fis = new FileInputStream(file);
                int fileSize = (int) file.length();
                byte[] bytes = new byte[fileSize];
                fis.read(bytes);
                Response response = uploadManager.put(bytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                removeFilePath = putRet.key;
            } catch (QiniuException ex) {
                LOGGER.error("上传文件到七牛", ex.fillInStackTrace());
            }
        } catch (Exception ex) {
            LOGGER.error("上传文件到七牛", ex.fillInStackTrace());
        }
        return removeFilePath;
    }

    public static void main(String[] args) {
        File file = new File("/home/liuzhiyuan/Downloads/20180126144707.png");
        FileUploadUtils.uploadFile(file, "file.png");
    }
}
